package com.sx.zongzhi.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.WorkLogAdapter;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.OrganizingBean;
import com.sx.zongzhi.bean.UserBean;
import com.sx.zongzhi.bean.UserPermission;
import com.sx.zongzhi.bean.WorkLogBean;
import com.sx.zongzhi.bean.WorkLogRefreshBean;
import com.sx.zongzhi.presenter.WorkLogPest;
import com.sx.zongzhi.utils.AppConstants;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.Global;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.IWorkLogView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

/**
 * 工作日志
 */
public class WorkLogActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener,
        View.OnClickListener, IWorkLogView {

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.imvAdd)
    ImageView imvAdd;
    @BindView(R.id.tv_Total)
    TextView tvTotal;
    private WorkLogAdapter workLogAdapter;
    private List<WorkLogBean> workLogBeanList = new ArrayList<>();
    private PopupWindow selectPop;

    private int page = 1, rows = 10;
    private String searchTitle = "", searchTimeStart = "", searchTimeEnd = "", orgId = "", workUser = "";
    private Disposable disposable;
    private UserPermission userPermission;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_household);
        ButterKnife.bind(this);
        setTitleName(R.string.work_log);
        imvAdd.setVisibility(View.GONE);
        setRightImage(R.mipmap.icon_nav_search);
        initView();
    }

    private void initView() {
        IDataStorage dataStorage= DataStorageFactory.getInstance(
                getApplicationContext(),
                DataStorageFactory.TYPE_DATABASE);
        UserBean userBean = dataStorage.load(UserBean.class,getPackageName());
        orgId = userBean.getId();
        if (!"片组片格".equals(userBean.getOrg().getOrgLevel().getDisplayName())){
            setRightImage2(R.mipmap.icon_nav_position);
        }
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setColorSchemeResources(AppConstants.colors);
            swipeRefreshLayout.setOnRefreshListener(this);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        workLogAdapter = new WorkLogAdapter(this, R.layout.item_work_log_list, workLogBeanList);
        workLogAdapter.setEmptyView(View.inflate(this, R.layout.load_error_view, null));
        recyclerView.setAdapter(workLogAdapter);
        workLogAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                page++;
                getData();
            }
        }, recyclerView);
        workLogAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(WorkLogActivity.this, WorkLogDetailActivity.class)
                        .putExtra("workLogBean", workLogBeanList.get(position))
                .putExtra("userPermission",userPermission));
            }
        });
        initRx();
        onRefresh();
    }

    private void initRx() {
        disposable = MyRxBus.get().toObservable(MsgEvent.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent bean) throws Exception {
                        if (bean.getRequest().equals("WorkLogActivity")) {
                            if (bean.getType() == 0) {//选组织结构
                                OrganizingBean oBean = (OrganizingBean) bean.getMsg();
                                if (oBean != null) {
                                    orgId = oBean.getId();
//                                    if (oBean.isGrid() && userPermission != null && userPermission.isAddWorkDiary()){
//                                        imvAdd.setVisibility(View.VISIBLE);
//                                    }else {
//                                        imvAdd.setVisibility(View.GONE);
//                                    }
                                }
                                page = 1;
                                getData();
                            } else if (bean.getType() == 2) {//筛选
                                WorkLogRefreshBean workLogRefreshBean = (WorkLogRefreshBean) bean.getMsg();
                                searchTitle = BaseUtil.isEmpty(workLogRefreshBean.searchTitle) ? "" : workLogRefreshBean.searchTitle;
                                searchTimeStart = BaseUtil.isEmpty(workLogRefreshBean.searchTimeStart) ? "" : workLogRefreshBean.searchTimeStart;
                                searchTimeEnd = BaseUtil.isEmpty(workLogRefreshBean.searchTimeEnd) ? "" : workLogRefreshBean.searchTimeEnd;
                                workUser = BaseUtil.isEmpty(workLogRefreshBean.workUser) ? "" : workLogRefreshBean.workUser;
                                page = 1;
                                getData();
                            }else if (bean.getType() != 2 && bean.getType() != 0) {
                                onRefresh();
                            }
                        }
                    }
                });
    }

    private void getData() {
        new WorkLogPest(this).getWorkLogList(this, page, rows, orgId, searchTitle, workUser, searchTimeStart, searchTimeEnd);
    }

    @OnClick({R.id.imv_Right, R.id.imv_Right2, R.id.imvAdd})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.imv_Right:
                startActivity(new Intent(WorkLogActivity.this, WorkLogSearchActivity.class));
                break;
            case R.id.imv_Right2:
                startActivity(new Intent(this, OrganizingActivity.class).
                        putExtra(Global.ACTIVITY_FRAGMENT, "WorkLogActivity"));
                break;
            case R.id.imvAdd:
                showPopupSelect();
                break;

        }
    }

    @Override
    public void onRefresh() {
        swipeRefreshLayout.setRefreshing(false);
        page = 1;
        searchTitle = "";
        searchTimeStart = "";
        searchTimeEnd = "";
        orgId = "";
        workUser = "";
        getData();
    }

    /**
     * 显示选择文件的弹窗
     */
    private void showPopupSelect() {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_select_file, null);
        if (selectPop == null) {
            selectPop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            selectPop.setTouchable(true);
            selectPop.setOutsideTouchable(false);
            selectPop.setBackgroundDrawable(new ColorDrawable(Color.alpha(128)));
        }
        view.findViewById(R.id.tv_File).setVisibility(View.GONE);
        view.findViewById(R.id.tv_Text).setVisibility(View.VISIBLE);
        view.findViewById(R.id.tv_Text).setOnClickListener(this);
        view.findViewById(R.id.tv_Audio).setOnClickListener(this);
        view.findViewById(R.id.tv_Video).setOnClickListener(this);
        view.findViewById(R.id.tv_Picture).setOnClickListener(this);
        view.findViewById(R.id.tv_Cancel).setOnClickListener(this);
        selectPop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_Cancel) {
            selectPop.dismiss();
            return;
        }
        int type = 10;
        switch (v.getId()){
            case R.id.tv_Text:
                type = 10;
                break;
            case R.id.tv_Audio:
                type = 30;
                break;
            case R.id.tv_Video:
                type = 50;
                break;
            case R.id.tv_Picture:
                type = 70;
        }
        selectPop.dismiss();
        startActivity(new Intent(this, AddWorkLogActivity.class)
                .putExtra("FileType", type));
    }

    @Override
    public void getWorkLogListSuccess(UserPermission userPermissions, List<WorkLogBean> workLogBeanLists, int total) {
        if (userPermissions != null){
            userPermission = userPermissions;
            if (userPermission.isAddWorkDiary()){
                imvAdd.setVisibility(View.VISIBLE);
            }else {
                imvAdd.setVisibility(View.GONE);
            }
        }
        if (page == 1) {
            workLogBeanList.clear();
            workLogAdapter.setNewData(workLogBeanList);
        }
        if (workLogBeanLists != null && workLogBeanLists.size() > 0) {
            workLogBeanList.addAll(workLogBeanLists);
        }
        if (workLogBeanList.size() >= total) {
            workLogAdapter.loadMoreEnd();
        }else {
            workLogAdapter.loadMoreComplete();
        }
        workLogAdapter.notifyDataSetChanged();
        tvTotal.setText( "共"+total + "条数据");
    }

    @Override
    public void showError(String message) {
        ToastUtils.showToast(WorkLogActivity.this, message);
    }
    @Override
    protected void onDestroy() {
        if (disposable != null){
            disposable.dispose();
        }
        super.onDestroy();
    }
}
